clear;
%% input: 
%  1. subject num
%  2. evaluation: pre / post       
%  3. task: fr / lr 
%  4. synergy component
%  5. load data folder & save .mat folder.

num_choose = {'05', '06', '07_1', '08', '09', '10', '11', '14', '16','17','18','19','20','22','23','25','26'};
eva_choose = {'pre','post'};
task_choose = {'FR','LR'};
component_choose = [2,3,4,5];

% fixed parameter
fs=1000;
mid=400;

% choose data path & save path
[subject_folder,synergy_sim_save,sep_typle] = file_path();

for si = 1:1:length(num_choose)
    subject_num = num_choose(si);
    
    for eva_i = 1:1:length(eva_choose)
        eva = eva_choose(eva_i);
        for task_i = 1:1:length(task_choose)
            task = task_choose(task_i);
            % subject data path:
            subject_data = strcat(subject_folder,'s',subject_num,'_',eva,sep_typle,task,sep_typle);        
            for syn_i = 1:1:length(component_choose)
                syn_component = component_choose(syn_i);
               %% calculation  EMG         
                Files = dir(subject_data{1,1});
                LengthFiles = length(Files);
                EMGMatrix = [];
                % preprocess EMG
                for j = 3:LengthFiles
                    % load raw data
                   [raw_data] = load_raw_data(subject_data,Files,j);% load raw data
                    % calculate onset & offset
                    [movement] = calculate_onset_offset( raw_data,fs,mid );
                
                    % EMG preprocess
                    [ EMG_p ] = EMG_preprocess( raw_data,movement); 
                    EMGMatrix = cat(1, EMGMatrix, EMG_p(1:1000,1:7));
                end
                %  decompose synergy(NNMF)
                for k = 1:1:7
                    [synergy_subject(k)] = NNMF_Sync(abs(EMGMatrix),k); % NNMF 
                end

                % save synergy decomposition.mat
                %save(strcat(cd,'//synergy_s',subject_num,'_',eva,'_',lower(task),'.mat'),'synergy_subject');

                % calculate synergy similarity
                [sim] = calculate_synergy_sim( synergy_subject,task,syn_component );
                sim_struct{syn_i,1} = sim;
            end
            
            % save similarity.mat
             save_path = strcat(synergy_sim_save,'synergy_sim_s',subject_num,'_',eva,'_',lower(task),'.mat');
             save(save_path{1,1},'sim_struct');
            
        end
    end
end



